/*
 *    Copyright 2021 Institute of Software Chinese Academy of Sciences, ISRC

 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

import prompt from '@system.prompt'
import router from '@system.router'
import http from '@ohos.net.http'
import util from '@ohos.util'
export default {
    data: {
        name: '',
        password: '',
        token: '',
        verified: '',
        httpRequest:{},
        success:{},
        session: '',
        userId: '',
    },
    onInit() {
        this.httpRequest = http.createHttp();
    },
    onDestroy() {
        this.httpRequest.destroy();
    },
    getName(e) {
        this.name = e.value;
        console.info("napi_name=" + this.name)
    },
    getPassword(e) {
        this.password = e.value;
        console.info("napi_date=" + this.password)
    },
    getVerifycode(e) {
        this.verified = e.value;
        console.info("napi_verified=" + this.verified)
    },
    onVerify() {
        let url = this.pic;
        this.$refs.canvas.clear();
        const el =this.$refs.canvas;
        var ctx =el.getContext('2d');
        ctx.clearRect(0, 0, 300, 200);
        var img = new Image();
        img.src = url;
        console.log('napi_Image load success1',img.src);
        img.onload = function() {
            console.log('napi_Image load success2');
            ctx.drawImage(img, 0, 0, 300, 200);
        };
        img.onerror = function() {
            console.log('napi_Image load fail');
        };
    },
    onLogin() {
        if (this.name.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.name_null')
            })
            return;
        }
        if (this.password.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.date_null')
            })
            return;
        }
        if (this.verified.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.gender_null')
            })
            return;
        }
        let url = this.$app.$def.data.usermgmtIP + '/login?verifyCode=' + this.verified
        this.httpRequest.on('napi_headersReceive', (data) => {
            console.info('napi_header: ' + data.header);
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.session + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.token + ';';
        console.info('myapp cookie_value: ' + cookie_value);
        let xd = 'username='+ this.name+'&password='+ this.password;
        this.httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Cookie': cookie_value,
                    'X-XSRF-TOKEN': this.token
                },
                extraData: xd,
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                this.success = data.responseCode;
            } else {
                console.info('napi_error:' + err);
                this.httpRequest.destroy();
            }
            if(this.success == 200) {
                this.$app.$def.data.name = this.name;
                this.$app.$def.data.password = this.password;
                console.info("myapp login cookies:" + JSON.stringify(data.cookies));
                this.$app.$def.data.session = data.cookies.substring(data.cookies.length-118, data.cookies.length-86);
                this.$app.$def.data.token = data.cookies.substring(data.cookies.length-36);
                this.session = data.cookies.substring(data.cookies.length-118, data.cookies.length-86);
                this.token = data.cookies.substring(data.cookies.length-36);
                console.info("myapp login user name:" + this.$app.$def.data.name);
                console.info("myapp login user password:" + this.$app.$def.data.password);
                this.onGetuserId();
                console.info("myapp this.token:" + this.token);
                console.info("myapp this.session:" + this.session);

                console.info("myapp page back to first");
                if (this.lastPage == "pages/index/index") {
                    router.push({
                        uri: "pages/index/index",

                    })
                } else if (this.lastPage == "pages/description/description") {
                    router.push({
                        uri: "pages/description/description",
                        params: {
                            appItem: this.appItem,
                        }
                    })
                }

            } else {
                var err = JSON.parse(data.result);
                console.error("myapp login err result:" + err.code);
                if (err.code == 70011) {
                    prompt.showToast({
                        message: "登录失败！验证码错误/过期"
                    })
                } else {
                    prompt.showToast({
                        message: "登录失败！请检查用户名/密码"
                    })
                }
            }
        }
        );

    },

    onGetuserId() {
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            //console.info('header: ' + data.header);
        });

        let url = this.$app.$def.data.usermgmtIP + "/auth/login-info";
        let session_value = 'AUTHSERVERSESSIONID=' + this.session + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.token + ';';
        console.info("myapp accesstoken cookie:" + cookie_value);
        console.info("myapp login-info url:" + url);
        console.info("myapp login-info url:" + cookie_value);

        httpRequest.request(

            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                console.info('myapp download code:' + data.responseCode);
                console.info('myapp userID Result:' + data.result);
                console.info('myapp (data.cookies)' + JSON.stringify(data.cookies));
                console.info('myapp userID:' + JSON.parse(data.result).userId);
                this.userId = JSON.parse(data.result).userId;
                this.$app.$def.data.userId = this.userId;
            } else {
                console.info('myapp download error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    get_all_token() {
        let url  = this.$app.$def.data.usermgmtIP + '/v1/identity/verifycode-image?t=' + Math.random()
        console.info('napi_header: ');
        this.httpRequest.on('napi_headersReceive', (data) => {
            console.info('napi_header: ' + data.header);
        });
        this.httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'image/jpeg',
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                var lresult = new Uint8Array(data.result);
                var that = new util.Base64();
                var finresult = that.encodeToStringSync(lresult);
                this.pic = "data:image/jpeg;base64," + finresult;
                this.onVerify();

                this.token = data.cookies.substring(data.cookies.length-137, data.cookies.length-94);
                this.session = data.cookies.substring(data.cookies.length-32);
                console.info('myapp login token:' + this.token);
                console.info('myapp login session:' + this.session);
            } else {
                console.info('napi_error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                this.httpRequest.destroy();
            }
        }
        );
    },
    onRegister(){
        router.push({
            uri: 'pages/register/register'
        })
    }
}
